import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import router from "@/router";
import { getToken, getTimeStamp } from "@/utils/auth";

// 设置超时时间
const timeOut = 3600;

// 创建一个axios对象
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // 设置超时时间
});
// 设置请求拦截
service.interceptors.request.use(
  async config => {
    if (store.getters.token) {
      if (isTimeOut()) {
        await store.dispatch("user/logout");
        Message.error("登录状态已过期,请重新登录！");
        router.push("/login");
        return;
      }

      config.headers.Authorization = "Bearer " + store.getters.token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 设置响应拦截
service.interceptors.response.use(
  response => {
    let res = response.data;
    if (res.success) {
      return res;
    } else {
      Message.error(res.message);
      return Promise.reject(res.message);
    }
  },
  async error => {
    if (error.response&&error.response.data&&error.response.data.code === 10002) {
      await store.dispatch("user/logout");
      Message.error("登录状态已过期,请重新登录！");
      router.push("/login");
      return;
    }

    return Promise.reject(error);
  }
);

function isTimeOut() {
  let timeStamp = getTimeStamp();
  let currentTime = Date.now();
  return (currentTime - timeStamp) / 1000 > timeOut;
}

export default service;
